﻿// ********************************************************************
//  文件名: MySocket.cs
//  描述:
//  作者: 胡宇辰
//  创建时间: 2024-3-18
// 
//  修改历史:
// ********************************************************************

using System.Net;
using System.Net.Sockets;
using System.Text;

namespace MyApp;

public class MySocket
{
    static Socket serverSocket;
    public static void Start()
    {
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6324));
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
        serverSocket.Listen(10);
        Console.WriteLine("Server started");
        new Thread(ListenFunction).Start();
    }
    
    static void ListenFunction()
    {
        while (true)
        {
            Socket clientSocket = serverSocket.Accept();
            Console.WriteLine("Client connected：" + clientSocket.RemoteEndPoint + "  " +clientSocket.LocalEndPoint);
            //开启一个线程，处理客户端请求
            var thread = new Thread(HandleClient!);
            thread.IsBackground = true;
            thread.Start(clientSocket);
        }
    }
        

    //处理客户端请求
    static void HandleClient(object obj)
    {
        if(!(obj is Socket clientSocket))
            return;

        byte[] buffer = new byte[1024 * 1024];
        while (true)
        {
            int length = clientSocket.Receive(buffer);
            if (length == 0)
            {
                Console.WriteLine("Client disconnected");
                break;
            }
            else
            {
                Console.WriteLine("Client sent: " + Encoding.UTF8.GetString(buffer, 0, length));
            }
        }
    }
}